  <script setup>
import { reactive, ref, computed, onMounted, onUnmounted, watch } from "vue";
import { Editor, EditorContent } from "@tiptap/vue-3";

import {QuestionCircleOutlined} from '@ant-design/icons-vue'
// 获取视频组纯文本方法
import { getSsmlcontent } from "@/common/utils/richTextProcessing";


// 富文本中的组件 每一项 自定义组件
import speak from "@/views/shotstack/MixedCutPlatforms/mixedCutCreat/components/Component/TextEditConfig/index.js";
// 插入停顿
import Break from "@/views/shotstack/MixedCutPlatforms/mixedCutCreat/components/Component/TextEditConfig/break.js";
// 取消诵读
import CancelRead from "@/views/shotstack/MixedCutPlatforms/mixedCutCreat/components/Component/TextEditConfig/cancelread.js";
// 数字读音
import NumberPronunciation from "@/views/shotstack/MixedCutPlatforms/mixedCutCreat/components/Component/TextEditConfig/numberPronunciation.js";
// 修改文字发音
import Pronounce from "@/views/shotstack/MixedCutPlatforms/mixedCutCreat/components/Component/TextEditConfig/pronounce.js";
// 字符数量限制 + 统计
import CharacterCount from "@tiptap/extension-character-count";

// import { Color } from '@tiptap/extension-color'
import TextStyle from '@tiptap/extension-text-style'
import StarterKit from '@tiptap/starter-kit'
import Document from "@tiptap/extension-document";
import Text from "@tiptap/extension-text";
import Placeholder from '@tiptap/extension-placeholder'

import EditBtns from "@/views/shotstack/MixedCutPlatforms/mixedCutCreat/components/Component/TextEditComponens/EditBtns.vue";

import { useStore } from "vuex";
const store = useStore();


const props = defineProps({
  // 选择的音色 - 不同平台的音色 下方的标签控制会不同
  voiceData: {
    type: Object,
    default() {
      return {}
    }
  },
  // 音色类型 为2(火山引擎) 的时候 隐藏标签控制按钮
  hiddenSSML: {
    type: Number,
    default: 2
  },
  maxlength:{
    type: Number,
    default: 2000
  },

  // 初始赋值
  initText: {
    type: String,
    default: ''
  }
})

const emit = defineEmits(["textChagne"]);

// 富文本实例
const editor = ref()

const state = reactive({
    max_text_length: 2000
})

// 富文本字数上限
const limit = ref(props.maxlength || state.max_text_length)

// 字数百分比
const percentage = computed(() => {
  return Math.round(
    (100 / limit.value) * editor.value?.storage.characterCount.characters()
  );
});

watch(
  () => editor.value?.storage.characterCount.characters(),
  (val) => {
    emit('textChagne')
  }
)

const init = () => {
    editor.value = new Editor({
        extensions: [
      StarterKit.configure({
        blockquote: false, // 在编辑器中使用html标签
        codeBlock: false, // 代码块儿
        heading: false, // 标题拓展
        horizontalRule: false, // 分割线
        orderedList: false, // ol > li 列表
      }),
      Placeholder.configure({
          placeholder: '请输入文案',
        }),
      Document,
      CancelRead,
      Break,
      NumberPronunciation,
      Pronounce,
      speak,
      TextStyle,
      // Color,
      Text,
      // 富文本字数限制
      CharacterCount.configure({
        limit: props.maxlength,
      }),
    ],
      content: props.initText
    })
}

// 获取当前富文本的文字字数
const text_num = computed(() => {
  if (!editor.value) return 0;
  return editor.value?.storage?.characterCount?.characters() || 0;
});

// 当前选区信息
const listenEditor = computed(() => {
  // debugger
  if (!editor.value) return null;
  const { state } = editor.value;
  // 选区为空
  if (state.selection.empty == true) {
    return false;
  } else {
    // 确保选区是文本选区
    // 使用 doc.textBetween 方法获取选区文本
    const text = state.doc.textBetween(
      state.selection.from,
      state.selection.to
    );
    // 存放选中的节点
    let selectedNodes = [];
    // 遍历每一个选区的范围
    state.selection.ranges.forEach((range) => {
      state.doc.nodesBetween(range.$from.pos, range.$to.pos, (node) => {
        if (node.type.name == "speak") {
          selectedNodes.push(node);
        }
      });
    });
    return {
      text,
      selectedNodes,
    };
  }
});

watch(
  () => listenEditor.value,
  (nv, ov) => {
    if (!nv) {
      store.commit("videoMixCut/SET_SELECTION_DATA", {});
      return;
    }
    // store.commit("videoMixCut/MODIFY_SUBTITLES_TTSCONFIG", { text: nv.text })
    store.commit("videoMixCut/SET_SELECTION_DATA", nv);
    console.log(nv, "选区改变");
  }
);


onMounted(() => {
    init()
})

onUnmounted(() => {
    editor.value.destroy()
})


// 获取当前富文本的内容
const getContent = () => {
  const json = editor.value.getJSON()
  const jsonArr = json.content.map(ele => ele.content)?.flat()
    console.log(jsonArr,'内容 arr');
    const textData = jsonArr?.[0] ? getSsmlcontent(jsonArr) : {
    text:'',
    ssml:`<speak></speak>`,
    isEmpty: true,
  }
    // const textData = getSsmlcontent(json.content?.[0]?.content??[])
    console.log(json,'获取的内容');
    console.log(textData, '获取的textData文本========');
    return {
        json,
        textData
    }
}


// 替换当前富文本的内容
const setContent = (content) => {
  editor.value?.commands?.setContent(content)
}

defineExpose({
  getContent,
  setContent
})
</script>
<template>
    <div class="editor_component">

        <div class="editor_controls" v-if="false">
            我是控制栏
        </div>


        <!-- 富文本主体 -->
        <div class="content">
      <editor-content :editor="editor"> </editor-content>

      <div class="btn_box">
        <!-- 底部btn按钮 :voiceData="props.voiceData" :hiddenSSML="props.hiddenSSML" -->
         <!-- <template v-if="typeof props.voiceData?.voice_type == 'number' && props.voiceData?.voice_type != props.hiddenSSML"> -->
           <!-- <EditBtns useType="数字人"  :editor="editor" style="outline: none"></EditBtns> -->
         <!-- </template> -->

        <div class="edit_show_msg">
          <!-- 文本字数进度 -->
          <div v-if="!!editor" :class="{
            'character-count': true,
            'character-count--warning':
              editor.storage.characterCount.characters() === limit,
          }">
            <svg height="20" width="20" viewBox="0 0 20 20">
              <circle r="10" cx="10" cy="10" fill="#e9ecef" />
              <circle r="5" cx="10" cy="10" fill="transparent" stroke="currentColor" stroke-width="10"
                :stroke-dasharray="`calc(${percentage} * 31.4 / 100) 31.4`" transform="rotate(-90) translate(-20)" />
              <circle r="6" cx="10" cy="10" fill="white" />
            </svg>
            {{ text_num }} / {{ limit }}
            <br />
          </div>

      <!-- <div class="tips" >
              <a-tooltip placement="top">
          <template #title>
            <span>字幕文案调整后，不影响已原有生成好的口播</span>
          </template>
          <QuestionCircleOutlined />
        </a-tooltip>
      </div> -->
        </div>
      </div>
    </div>

    </div>
</template>


<style lang="less" scoped>

    .editor_component{
        // height: 100%;
        // height: 470px;
      // margin-left: 10px;
      padding-left: 1px;
        width: 100%;
        display: flex;
        flex-direction: column;
        gap: 10px;
        .editor_controls{
            line-height: 2;
            background-color: rgba(135, 207, 235, 0.479);
        }
  // 富文本
  .content {
    // flex: 1;
    background-color: #ffffff;
    padding-bottom: 10px;

    :deep(.ProseMirror) {
      // outline: none !important;
    outline-color: var(--ss-primary-color);
    // height: 120px !important;
    max-height: 120px !important;
    width: 100%;
    padding: 10px;
    overflow-y: auto;
    border: 1px dashed #e3e2e2;
    border-radius: 8px;

    &::-webkit-scrollbar {
        width: 6px; /* 滚动条的宽度 */
        height: 10px; /* 滚动条的高度，垂直滚动条可能用得上 */
    }
    &::-webkit-scrollbar-thumb {
        background: #888; /* 滑块的背景颜色 */
        border-radius: 10px; /* 滑块的圆角 */
    }

    }

    .btn_box {
        margin-top: 10px;
      padding: 0 10px;
      padding-left: 0;
      display: flex;
      align-items: center;
      justify-content: space-between;

      .edit_show_msg {
        display: flex;
        align-items: center;
        gap: 10px;

        .tips {
          color: #737a87;

          .time_content {
            // color: var(--ss-primary-5);
          }
        }

        // 文本上限提示
        .character-count {
          align-items: center;
          color: var(--ss-primary-5);
          display: flex;
          font-size: 0.75rem;
          gap: 0.5rem;

          svg {
            color: var(--ss-primary-5);
          }

          &--warning,
          &--warning svg {
            color: red;
          }
        }
      }
    }
  }

    }

    // 使Placeholder显示
    :deep(.is-editor-empty:first-child){
      &::before {
      color: #adb5bd ;
      content: attr(data-placeholder) ;
      float: left ;
      height: 0 ;
      pointer-events: none ;
    }
    }

</style>